<template>
  <div class="file-manager">
    <!-- 顶部导航栏 -->
    <el-row class="header" :gutter="20">
      <el-col :span="12">
        <h1>文件管理中心</h1>
      </el-col>

      <el-col :span="12" class="header-actions">
        <el-input placeholder="搜索文件和文件夹..." v-model="searchQuery" class="search-input">
          <template #prefix>
            <Search class="el-input__icon" />
          </template>
        </el-input>
        <!-- 已删除头像展示部分 -->
      </el-col>
    </el-row>

    <!-- 路径导航（面包屑） -->
    <el-breadcrumb class="breadcrumb" separator="/">
      <el-breadcrumb-item @click="navigateToRoot">
        <Home class="breadcrumb-icon" />
        <span>根目录</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item v-for="(folder, index) in currentPath" :key="folder.id" @click="navigateToPath(index)">
        <Folder class="breadcrumb-icon" />
        <span>{{ folder.name }}</span>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 操作工具栏 -->
    <el-card class="toolbar">
      <div class="toolbar-buttons">
        <el-upload ref="uploadRef" :action="`http://localhost:5177/api/file/upload`" :headers="uploadHeaders"
          :on-success="handleUploadSuccess" :on-error="handleUploadError" :on-progress="handleUploadProgress"
          :before-upload="beforeUpload" :show-file-list="false" multiple
          :accept="'image/*,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.zip,.rar,.txt'">
          <el-button type="primary" class="action-button" v-if="hasPermission(null, 'create')">
            <Upload2 class="button-icon" />
            <span>上传文件</span>
          </el-button>
        </el-upload>
        <el-button type="success" @click="showCreateFolderDialog = true" class="action-button"
          v-if="hasPermission(null, 'create')">
          <FolderAdd class="button-icon" />
          <span>新建文件夹</span>
        </el-button>
        <el-button link @click="refreshFiles" :loading="loading" class="icon-button">
          <Refresh />
        </el-button>
      </div>
    </el-card>

    <!-- 权限提示 -->
    <el-alert v-if="showPermissionAlert" title="您没有执行此操作的权限" type="warning" show-icon :closable="true"
      @close="showPermissionAlert = false" class="permission-alert" />

    <!-- 文件夹区域 -->
    <div class="section">
      <h2 class="section-title">文件夹</h2>
      <!-- 文件夹列表 -->
      <el-card v-for="folder in filteredFolders" :key="folder.id" class="single-item-card">
        <div class="single-item-content">
          <div class="item-icon">
            <Folder class="folder-icon" />
          </div>
          <div class="item-info">
            <div class="item-name" @click="navigateToFolder(folder)" v-if="hasPermission(folder, 'read')">
              {{ folder.name }}
            </div>
            <div class="item-name no-permission" v-else>
              {{ folder.name }} <span class="permission-tag">无访问权限</span>
            </div>
            <div class="item-meta">
              <span>{{ folder.itemCount }} 个项目</span>
              <span>{{ formatDate(folder.updatedAt) }}</span>
              <span v-if="!isOwner(folder)" class="owner-info">
                所有者: {{ folder.ownerName || '未知' }}
              </span>
              <span class="permission-label">
                权限: {{ getPermissionLabel(folder.permissions?.access) }}
              </span>
            </div>
          </div>
          <div class="item-actions" v-if="hasPermission(folder, 'read')">
            <el-button size="small" @click.stop="openEditDialog(folder)" class="action-button"
              v-if="hasPermission(folder, 'write')">
              <Edit class="button-icon" />
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click.stop="confirmDelete(folder)" class="action-button"
              v-if="hasPermission(folder, 'delete')">
              <Delete class="button-icon" />
              <span>删除</span>
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 新建文件夹按钮 -->
      <el-card class="single-item-card add-item-card" @click="showCreateFolderDialog = true"
        v-if="hasPermission(null, 'create')">
        <div class="single-item-content">
          <div class="item-icon">
            <Plus class="plus-icon" />
          </div>
          <div class="item-info">
            <div class="item-name">新建文件夹</div>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="filteredFolders.length === 0 && !loading" class="empty-state">
        <el-empty description="没有文件夹"></el-empty>
      </div>
    </div>

    <!-- 文件区域 -->
    <div class="section">
      <h2 class="section-title">文件</h2>

      <!-- 文件列表 -->
      <el-card v-for="file in filteredFiles" :key="file.id" class="single-item-card">
        <div class="single-item-content">
          <div class="item-icon">
            <component v-if="!isImageFile(file.extension) && hasPermission(file, 'read')"
              :is="getFileIconComponent(file.extension)" class="file-icon" />
            <img v-if="isImageFile(file.extension) && hasPermission(file, 'read')" :src="file.url" :alt="file.name"
              class="file-icon-img" @click="previewFile(file)" style="cursor: pointer">
            <File v-else class="file-icon" />
          </div>
          <div class="item-info">
            <div class="item-name" @click="hasPermission(file, 'read') && previewFile(file)"
              :class="{ 'no-permission': !hasPermission(file, 'read') }">
              {{ file.name }}
              <span class="permission-tag" v-if="!hasPermission(file, 'read')">无访问权限</span>
            </div>
            <div class="item-meta">
              <span>{{ getFileTypeName(file.extension) }}</span>
              <span>{{ formatFileSize(file.size) }}</span>
              <span>{{ formatDate(file.updatedAt) }}</span>
              <span v-if="!isOwner(file)" class="owner-info">
                所有者: {{ file.ownerName || '未知' }}
              </span>
              <span class="permission-label">
                权限: {{ getPermissionLabel(file.permissions?.access) }}
              </span>
            </div>
          </div>
          <div class="item-actions" v-if="hasPermission(file, 'read')">
            <el-button size="small" @click.stop="downloadFile(file)" class="action-button"
              v-if="hasPermission(file, 'download')">
              <Download class="button-icon" />
              <span>下载</span>
            </el-button>
            <el-button size="small" @click.stop="openEditDialog(file)" class="action-button"
              v-if="hasPermission(file, 'write')">
              <Edit class="button-icon" />
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click.stop="confirmDelete(file)" class="action-button"
              v-if="hasPermission(file, 'delete')">
              <Delete class="button-icon" />
              <span>删除</span>
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="filteredFiles.length === 0 && !loading" class="empty-state">
        <el-empty description="没有文件"></el-empty>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-card>
          <div class="loading-content">
            <el-spinner></el-spinner>
            <p>加载中...</p>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog v-model="showFilePreview" :title="previewFileData.name" :width="isPreviewFullscreen ? '90%' : '800px'"
      :fullscreen="isPreviewFullscreen">
      <div v-if="previewLoading" class="preview-loading">
        <el-spinner></el-spinner>
        <p>加载文件中...</p>
      </div>

      <div v-else-if="previewError" class="preview-error">
        <Error class="error-icon" />
        <p>{{ previewError }}</p>
      </div>

      <div v-else class="preview-content">
        <!-- 图片预览 -->
        <div v-if="isImageFile(previewFileData.extension)" class="image-preview">
          <div class="image-controls">
            <el-button size="mini" @click="zoomImage(0.1)" class="action-button">
              <ZoomIn class="button-icon" />
              <span>放大</span>
            </el-button>
            <el-button size="mini" @click="zoomImage(-0.1)" class="action-button">
              <ZoomOut class="button-icon" />
              <span>缩小</span>
            </el-button>
            <el-button size="mini" @click="rotateImage(-90)" class="action-button">
              <RefreshLeft class="button-icon" />
              <span>左旋转</span>
            </el-button>
            <el-button size="mini" @click="rotateImage(90)" class="action-button">
              <RefreshRight class="button-icon" />
              <span>右旋转</span>
            </el-button>
            <el-button size="mini" @click="resetImageTransform" class="action-button">
              <Picture class="button-icon" />
              <span>重置</span>
            </el-button>
            <el-button size="mini" @click="isPreviewFullscreen = !isPreviewFullscreen" class="action-button">
              <Maximize2 class="button-icon" />
              <span>{{ isPreviewFullscreen ? '退出全屏' : '全屏查看' }}</span>
            </el-button>
          </div>
          <div class="image-container" :style="{ transform: `scale(${imageScale}) rotate(${imageRotation}deg)` }">
            <img :src="previewFileData.url" :alt="previewFileData.name" class="preview-image"
              @load="previewLoading = false">
          </div>
          <div class="image-info">
            <p>尺寸: {{ previewFileData.width }} × {{ previewFileData.height }} 像素</p>
            <p>大小: {{ formatFileSize(previewFileData.size) }}</p>
          </div>
        </div>

        <!-- 文本文件预览 -->
        <div v-else-if="isTextFile(previewFileData.extension)" class="text-preview">
          <pre>{{ previewFileContent }}</pre>
        </div>

        <!-- 其他文件类型 -->
        <div v-else class="other-file-preview">
          <component :is="getFileIconComponent(previewFileData.extension)" class="large-icon" />
          <p>无法预览此类型文件</p>
          <el-button type="primary" @click="downloadFile(previewFileData)" class="action-button"
            v-if="hasPermission(previewFileData, 'download')">
            <Download class="button-icon" />
            <span>下载文件</span>
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="showFilePreview = false" class="action-button">
          <span>关闭</span>
        </el-button>
        <el-button type="primary" @click="downloadFile(previewFileData)" class="action-button"
          v-if="hasPermission(previewFileData, 'download')">
          <Download class="button-icon" />
          <span>下载</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 创建文件夹对话框 -->
    <el-dialog v-model="showCreateFolderDialog" title="新建文件夹" :width="300">
      <el-form :model="newFolder" ref="folderForm" :rules="folderRules">
        <el-form-item prop="name">
          <el-input v-model="newFolder.name" placeholder="请输入文件夹名称"></el-input>
        </el-form-item>
        <el-form-item label="权限设置" v-if="currentUser.role === 'admin'">
          <el-radio-group v-model="newFolder.permission">
            <el-radio label="private">私有 (仅自己可见)</el-radio>
            <el-radio label="public">公开 (所有人可查看)</el-radio>
            <el-radio label="readonly">只读 (所有人可查看，不可修改)</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateFolderDialog = false" class="action-button">
          <span>取消</span>
        </el-button>
        <el-button type="primary" @click="createFolder" class="action-button">
          <span>创建</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框（整合重命名和权限设置） -->
    <el-dialog v-model="showEditDialog" :title="`编辑${editItemData.type === 'folder' ? '文件夹' : '文件'}`" :width="400">
      <el-form :model="editItemData" ref="editForm" :rules="editRules">
        <el-form-item prop="name">
          <el-input v-model="editItemData.name"
            :placeholder="`请输入${editItemData.type === 'folder' ? '文件夹' : '文件'}名称`"></el-input>
        </el-form-item>
        <el-form-item label="访问权限" v-if="canEditPermission">
          <el-select v-model="editItemData.permission" placeholder="请选择访问权限">
            <el-option label="私有 (仅自己可见)" value="private"></el-option>
            <el-option label="公开 (所有人可查看)" value="public"></el-option>
            <el-option label="只读 (所有人可查看，不可修改)" value="readonly"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false" class="action-button">
          <span>取消</span>
        </el-button>
        <el-button type="primary" @click="confirmEdit" class="action-button">
          <span>保存</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="showDeleteDialog" title="确认删除" :width="300">
      <p>您确定要删除 <span class="text-bold">{{ deleteItemData.name }}</span> 吗？</p>
      <p v-if="deleteItemData.type === 'folder'" class="text-danger">
        此操作将删除文件夹及其包含的所有内容，且不可撤销
      </p>
      <p v-else class="text-danger">此操作不可撤销</p>
      <template #footer>
        <el-button @click="showDeleteDialog = false" class="action-button">
          <span>取消</span>
        </el-button>
        <el-button type="danger" @click="deleteItem" class="action-button">
          <span>确认删除</span>
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/stores/auth';
import { fileApi } from '@/api/file';

// 引入图标组件
import {
  Search, FolderAdd, Refresh, Folder, Plus, Edit, Delete,
  RefreshLeft, RefreshRight, Picture, Upload2
} from '@element-plus/icons-vue';

// 状态管理
const searchQuery = ref('');
const currentFolderId = ref('root');
const currentPath = ref([]);
const items = ref([]);
const loading = ref(false);
const showPermissionAlert = ref(false);
const uploadRef = ref(null);

// 对话框状态
const showCreateFolderDialog = ref(false);
const showEditDialog = ref(false);
const showDeleteDialog = ref(false);
const showFilePreview = ref(false);

// 表单数据
const newFolder = ref({
  name: '',
  permission: 'private' // 默认私有
});
const editItemData = ref({ id: '', name: '', type: '', permission: 'private' });
const deleteItemData = ref({ id: '', name: '', type: '' });

// 文件预览相关
const previewFileData = ref({});
const previewFileContent = ref('');
const previewLoading = ref(false);
const previewError = ref('');
const isPreviewFullscreen = ref(false);

// 图片预览相关状态
const imageScale = ref(1);
const imageRotation = ref(0);

// 获取当前用户信息
const authStore = useAuthStore();
const currentUser = computed(() => ({
  id: authStore.user?.id || 'user1',
  name: authStore.user?.username || '管理员',
  role: authStore.user?.role || 'admin' // 默认管理员角色
}));

// 计算属性：是否可以编辑权限
const canEditPermission = computed(() => {
  return currentUser.value.role === 'admin' || isOwner(editItemData.value);
});

// 表单规则
const folderRules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' },
    { validator: validateFileName, trigger: 'blur' }
  ]
};

const editRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { validator: validateFileName, trigger: 'blur' }
  ]
};

// 过滤后的文件和文件夹（只显示有权限访问的）
const filteredItems = computed(() => {
  let result = items.value;

  // 先过滤掉没有读取权限的项目
  result = result.filter(item => hasPermission(item, 'read'));

  // 再应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(item =>
      item.name.toLowerCase().includes(query)
    );
  }

  return result;
});

const filteredFolders = computed(() => {
  return filteredItems.value.filter(item => item.type === 'folder');
});

const filteredFiles = computed(() => {
  return filteredItems.value.filter(item => item.type === 'file');
});

// 权限检查函数
function hasPermission(item, action) {
  // 没有具体项目，检查全局权限（如创建权限）
  if (!item) {
    // 管理员和所有者有创建权限
    return ['admin', 'owner'].includes(currentUser.value.role);
  }

  // 项目级权限检查
  const isOwner = item.ownerId === currentUser.value.id;

  // 管理员和所有者拥有所有权限
  if (currentUser.value.role === 'admin' || isOwner) return true;

  // 根据项目权限设置和操作类型判断
  const permissions = item.permissions || { access: 'private' };

  switch (action) {
    case 'read':
      // 管理员、所有者、公开、只读都能查看
      return currentUser.value.role === 'admin' || isOwner || ['public', 'readonly'].includes(permissions.access);
    case 'write':
    case 'delete':
      // 管理员、所有者、可写权限允许修改和删除
      return currentUser.value.role === 'admin' || isOwner || (permissions.access === 'public' && currentUser.value.role === 'editor');
    case 'download':
      // 管理员、所有者、公开、只读都能下载
      return currentUser.value.role === 'admin' || isOwner || ['public', 'readonly'].includes(permissions.access);
    case 'create':
      // 创建权限通常基于用户角色
      return currentUser.value.role !== 'viewer';
    default:
      return false;
  }
}

// 检查是否为所有者
function isOwner(item) {
  return item && item.ownerId === currentUser.value.id;
}

// 获取权限标签文本
function getPermissionLabel(permission) {
  switch (permission) {
    case 'private':
      return '私有';
    case 'public':
      return '公开';
    case 'readonly':
      return '只读';
    default:
      return '未知';
  }
}

// 初始化数据
function initData() {
  const storedData = localStorage.getItem('fileManagerData');

  if (!storedData) {
    const initialData = {
      users: [
        { id: 'user1', name: '管理员', role: 'admin' },
        { id: 'user2', name: '编辑', role: 'editor' },
        { id: 'user3', name: '查看者', role: 'viewer' }
      ],
      folders: [
        {
          id: 'folder1',
          name: '图片库',
          type: 'folder',
          itemCount: 5,
          updatedAt: new Date().toISOString(),
          ownerId: 'user1',
          ownerName: '管理员',
          permissions: { access: 'public' }
        },
        {
          id: 'folder2',
          name: '文档',
          type: 'folder',
          itemCount: 3,
          updatedAt: new Date().toISOString(),
          ownerId: 'user1',
          ownerName: '管理员',
          permissions: { access: 'readonly' }
        },
        {
          id: 'folder3',
          name: '私人文件夹',
          type: 'folder',
          itemCount: 2,
          updatedAt: new Date().toISOString(),
          ownerId: 'user2',
          ownerName: '编辑',
          permissions: { access: 'private' }
        }
      ],
      files: [
        {
          id: 'file1',
          name: '风景照.jpg',
          type: 'file',
          extension: 'jpg',
          size: 2048000, // 2MB
          updatedAt: new Date().toISOString(),
          ownerId: 'user1',
          ownerName: '管理员',
          url: 'https://picsum.photos/id/10/800/600',
          width: 800,
          height: 600,
          permissions: { access: 'public' }
        },
        {
          id: 'file2',
          name: '工作报告.docx',
          type: 'file',
          extension: 'docx',
          size: 1024000, // 1MB
          updatedAt: new Date().toISOString(),
          ownerId: 'user1',
          ownerName: '管理员',
          permissions: { access: 'readonly' }
        },
        {
          id: 'file3',
          name: '数据统计.xlsx',
          type: 'file',
          extension: 'xlsx',
          size: 1536000, // 1.5MB
          updatedAt: new Date().toISOString(),
          ownerId: 'user1',
          ownerName: '管理员',
          permissions: { access: 'private' }
        },
        {
          id: 'file4',
          name: '资料压缩包.zip',
          type: 'file',
          extension: 'zip',
          size: 3072000, // 3MB
          updatedAt: new Date().toISOString(),
          ownerId: 'user2',
          ownerName: '编辑',
          permissions: { access: 'public' }
        },
        {
          id: 'file5',
          name: '城市夜景.png',
          type: 'file',
          extension: 'png',
          size: 3072000, // 3MB
          updatedAt: new Date().toISOString(),
          ownerId: 'user2',
          ownerName: '编辑',
          url: 'https://picsum.photos/id/42/1200/800',
          width: 1200,
          height: 800,
          permissions: { access: 'private' }
        }
      ]
    };

    localStorage.setItem('fileManagerData', JSON.stringify(initialData));
    return initialData;
  }

  return JSON.parse(storedData);
}

// 获取数据
function getData() {
  return JSON.parse(localStorage.getItem('fileManagerData') || '{"folders":[],"files":[],"users":[]}');
}

// 保存数据
function saveData(data) {
  localStorage.setItem('fileManagerData', JSON.stringify(data));
}

// 加载文件列表
async function fetchFiles(folderId = 'root') {
  try {
    loading.value = true;

    // 调用真实的API获取文件列表
    const response = await fileApi.getFileList({
      pageIndex: 1,
      pageSize: 100 // 暂时获取所有文件
    });

    if (response.code === 200) {
      // 将API返回的文件数据转换为组件需要的格式
      const files = response.data.items.map(file => ({
        id: file.id,
        name: file.originalName || file.name,
        type: 'file',
        extension: getFileExtension(file.originalName || file.name),
        size: file.size,
        updatedAt: file.createdAt,
        ownerId: file.userId || 'current-user',
        ownerName: file.username || '当前用户',
        url: file.url || file.path,
        permissions: { access: 'private' } // 默认私有，后续可根据实际权限设置
      }));

      // 暂时只显示文件，文件夹功能可以后续扩展
      items.value = files;
      currentFolderId.value = folderId;
      currentPath.value = []; // 暂时没有文件夹层级
    } else {
      throw new Error(response.msg || '获取文件列表失败');
    }
  } catch (error) {
    console.error('获取文件列表失败:', error);
    ElMessage.error('加载文件失败: ' + error.message);
    // 如果API失败，使用模拟数据
    const data = getData();
    items.value = [...data.folders, ...data.files];
  } finally {
    loading.value = false;
  }
}

// 辅助函数：获取文件扩展名
function getFileExtension(filename) {
  return filename.split('.').pop()?.toLowerCase() || '';
}

// 文件夹导航
function navigateToFolder(folder) {
  if (!hasPermission(folder, 'read')) {
    showPermissionAlert.value = true;
    return;
  }
  fetchFiles(folder.id);
}

// 导航到根目录
function navigateToRoot() {
  fetchFiles('root');
}

// 导航到路径中的某个文件夹
function navigateToPath(index) {
  const targetFolder = currentPath.value[index];
  if (targetFolder) {
    // 重置路径到目标文件夹
    currentPath.value = currentPath.value.slice(0, index + 1);
    fetchFiles(targetFolder.id);
  }
}

// 刷新文件列表
function refreshFiles() {
  fetchFiles(currentFolderId.value);
}

// 创建文件夹
async function createFolder() {
  if (!hasPermission(null, 'create')) {
    showPermissionAlert.value = true;
    return;
  }

  try {
    const data = getData();

    // 检查同名文件夹
    const hasSameName = data.folders.some(
      folder => folder.name === newFolder.value.name
    );

    if (hasSameName) {
      ElMessage.warning('已存在同名文件夹');
      return;
    }

    const newFolderObj = {
      id: `folder_${Date.now()}`,
      name: newFolder.value.name,
      type: 'folder',
      itemCount: 0,
      updatedAt: new Date().toISOString(),
      ownerId: currentUser.value.id,
      ownerName: currentUser.value.name,
      permissions: { access: newFolder.value.permission }
    };

    data.folders.push(newFolderObj);
    saveData(data);

    ElMessage.success('文件夹创建成功');
    showCreateFolderDialog.value = false;
    newFolder.value.name = '';
    newFolder.value.permission = 'private';
    fetchFiles(currentFolderId.value);
  } catch (error) {
    ElMessage.error('创建文件夹失败: ' + error.message);
  }
}

// 打开编辑对话框
function openEditDialog(item) {
  if (!hasPermission(item, 'write')) {
    showPermissionAlert.value = true;
    return;
  }

  editItemData.value = {
    id: item.id,
    name: item.name,
    type: item.type,
    permission: item.permissions?.access || 'private'
  };
  showEditDialog.value = true;
}

// 确认编辑（包含重命名和权限修改）
async function confirmEdit() {
  try {
    const data = getData();
    const { id, name, type, permission } = editItemData.value;

    // 检查权限
    const item = data[type + 's'].find(item => item.id === id);
    if (!hasPermission(item, 'write')) {
      showPermissionAlert.value = true;
      return;
    }

    // 检查同名
    const hasSameName = data[type + 's'].some(
      item => item.id !== id && item.name === name
    );

    if (hasSameName) {
      ElMessage.warning(`已存在同名${type === 'folder' ? '文件夹' : '文件'}`);
      return;
    }

    // 更新项目信息
    const index = data[type + 's'].findIndex(item => item.id === id);
    if (index !== -1) {
      // 更新名称
      data[type + 's'][index].name = name;

      // 只有所有者或管理员可以更新权限
      if (canEditPermission.value) {
        data[type + 's'][index].permissions = {
          ...data[type + 's'][index].permissions,
          access: permission
        };
      }

      data[type + 's'][index].updatedAt = new Date().toISOString();
      saveData(data);

      ElMessage.success('编辑成功');
      showEditDialog.value = false;
      fetchFiles(currentFolderId.value);
    }
  } catch (error) {
    ElMessage.error('编辑失败: ' + error.message);
  }
}

// 上传功能
const uploadHeaders = computed(() => {
  const authStore = useAuthStore();
  return {
    'Authorization': `Bearer ${authStore.token}`
  };
});

// 上传前检查
function beforeUpload(file) {
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    ElMessage.error(`文件 ${file.name} 超过大小限制(10MB)`);
    return false;
  }
  return true;
}

// 上传成功
function handleUploadSuccess(response, file) {
  if (response.code === 200) {
    ElMessage.success(`${file.name} 上传成功`);
    // 刷新文件列表
    refreshFiles();
  } else {
    ElMessage.error(`${file.name} 上传失败: ${response.msg || '未知错误'}`);
  }
}

// 上传失败
function handleUploadError(error, file) {
  console.error('上传失败:', error);
  ElMessage.error(`${file.name} 上传失败`);
}

// 上传进度
function handleUploadProgress(event, file) {
  // 可以在这里显示上传进度，但我们保持简单
  console.log(`${file.name} 上传进度: ${Math.round(event.percent)}%`);
}

// 文件预览
function previewFile(file) {
  if (!hasPermission(file, 'read')) {
    showPermissionAlert.value = true;
    return;
  }

  previewFileData.value = { ...file };
  previewFileContent.value = '';
  previewError.value = '';
  previewLoading.value = true;
  showFilePreview.value = true;
  // 重置图片变换参数
  imageScale.value = 1;
  imageRotation.value = 0;

  // 模拟加载延迟
  if (!isImageFile(file.extension)) {
    setTimeout(() => {
      previewLoading.value = false;

      // 文本文件预览内容
      if (isTextFile(file.extension)) {
        previewFileContent.value = '这是文本文件的示例内容...\n\n第二行内容\n第三行内容';
      }
    }, 500);
  }
}

// 图片预览控制
function zoomImage(delta) {
  imageScale.value = Math.max(0.1, Math.min(5, imageScale.value + delta));
}

function rotateImage(degrees) {
  imageRotation.value = (imageRotation.value + degrees) % 360;
}

function resetImageTransform() {
  imageScale.value = 1;
  imageRotation.value = 0;
}

// 下载文件
async function downloadFile(file) {
  if (!hasPermission(file, 'download')) {
    showPermissionAlert.value = true;
    return;
  }

  try {
    ElMessage.info(`开始下载 ${file.name}`);

    // 调用文件下载API
    const response = await fileApi.downloadFile(file.id);

    // 创建下载链接
    const blob = new Blob([response]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success(`${file.name} 下载完成`);
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(`下载 ${file.name} 失败: ${error.message}`);
  }
}

// 删除操作
function confirmDelete(item) {
  if (!hasPermission(item, 'delete')) {
    showPermissionAlert.value = true;
    return;
  }

  deleteItemData.value = {
    id: item.id,
    name: item.name,
    type: item.type
  };
  showDeleteDialog.value = true;
}

async function deleteItem() {
  try {
    const data = getData();
    const { id, type } = deleteItemData.value;

    // 检查权限
    const item = data[type + 's'].find(item => item.id === id);
    if (!hasPermission(item, 'delete')) {
      showPermissionAlert.value = true;
      showDeleteDialog.value = false;
      return;
    }

    // 对于文件夹，执行级联删除
    if (type === 'folder') {
      // 1. 先删除文件夹内的所有文件
      const filesToDelete = data.files.filter(() => {
        // 实际应用中这里应该根据文件夹ID筛选子文件
        // 这里简化处理，仅作示例
        return true;
      });

      filesToDelete.forEach(fileItem => {
        const fileIndex = data.files.findIndex(f => f.id === fileItem.id);
        if (fileIndex !== -1) {
          data.files.splice(fileIndex, 1);
        }
      });

      // 2. 再删除子文件夹
      const subfoldersToDelete = data.folders.filter(folder => {
        // 实际应用中这里应该根据父文件夹ID筛选子文件夹
        // 这里简化处理，仅作示例
        return folder.id !== id && folder.name.includes(deleteItemData.value.name);
      });

      subfoldersToDelete.forEach(folder => {
        const folderIndex = data.folders.findIndex(f => f.id === folder.id);
        if (folderIndex !== -1) {
          data.folders.splice(folderIndex, 1);
        }
      });
    }

    // 3. 删除当前项目
    const index = data[type + 's'].findIndex(item => item.id === id);
    if (index !== -1) {
      data[type + 's'].splice(index, 1);
      saveData(data);

      ElMessage.success('删除成功');
      showDeleteDialog.value = false;
      fetchFiles(currentFolderId.value);
    }
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message);
  }
}

// 验证文件名
function validateFileName(rule, value, callback) {
  const invalidChars = /[\\/:*?"<>|]/;
  if (invalidChars.test(value)) {
    callback(new Error('名称不能包含 \\ / : * ? " < > | 这些字符'));
  } else if (value.length > 50) {
    callback(new Error('名称长度不能超过50个字符'));
  } else {
    callback();
  }
}

// 工具函数 - 获取文件图标组件（适配全局注册）
function getFileIconComponent(extension) {
  if (!extension) return 'File';

  switch (extension.toLowerCase()) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      return 'Picture';
    case 'doc':
    case 'docx':
      return 'Document';
    case 'xls':
    case 'xlsx':
      return 'Table';
    case 'ppt':
    case 'pptx':
      return 'Present';
    case 'pdf':
      return 'FilePdf';
    case 'txt':
      return 'FileText';
    case 'zip':
    case 'rar':
      return 'Archive'; // 全局注册的图标组件
    default:
      return 'File';
  }
}

// 工具函数 - 获取文件类型名称
function getFileTypeName(extension) {
  if (!extension) return '文件';

  switch (extension.toLowerCase()) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      return '图片';
    case 'doc':
    case 'docx':
      return 'Word文档';
    case 'xls':
    case 'xlsx':
      return 'Excel表格';
    case 'ppt':
    case 'pptx':
      return '演示文稿';
    case 'pdf':
      return 'PDF文档';
    case 'txt':
      return '文本文件';
    case 'zip':
    case 'rar':
      return '压缩文件';
    default:
      return '文件';
  }
}

// 工具函数 - 判断是否为图片文件
function isImageFile(extension) {
  if (!extension) return false;
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  return imageExtensions.includes(extension.toLowerCase());
}

// 工具函数 - 判断是否为文本文件
function isTextFile(extension) {
  if (!extension) return false;
  const textExtensions = ['txt', 'html', 'css', 'js', 'json', 'md'];
  return textExtensions.includes(extension.toLowerCase());
}

// 工具函数 - 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 工具函数 - 格式化日期
function formatDate(dateString) {
  if (!dateString) return '';

  const date = new Date(dateString);
  return date.toLocaleString();
}

// 组件挂载时初始化
onMounted(() => {
  initData();
  fetchFiles();
});
</script>

<style scoped>
.file-manager {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
  align-items: center;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 300px;
}

/* 面包屑导航样式 */
.breadcrumb {
  margin-bottom: 20px;
  padding: 8px 0;
}

.breadcrumb-icon {
  margin-right: 5px;
  width: 1em;
  height: 1em;
}

.el-breadcrumb__item {
  cursor: pointer;
}

.el-breadcrumb__item:last-child {
  color: #409eff;
  font-weight: 500;
}

.toolbar {
  margin-bottom: 20px;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
}

.permission-alert {
  margin-bottom: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-container {
  padding: 40px 20px;
  text-align: center;
  border: 2px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-container.drag-over {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.upload-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 15px;
}

.browse-button {
  margin-top: 20px;
}

.upload-progress {
  margin-bottom: 20px;
}

.progress-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.progress-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.image-thumbnail {
  margin-bottom: 10px;
}

.preview-thumb {
  width: 60px;
  height: auto;
  border-radius: 4px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.file-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}

.file-percentage {
  margin-right: 10px;
  min-width: 40px;
  text-align: right;
}

.upload-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.compression-info {
  color: #67c23a;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  margin-bottom: 15px;
  font-size: 18px;
  color: #303133;
}

/* 单个项目卡片样式 */
.single-item-card {
  margin-bottom: 10px;
  transition: all 0.2s;
}

.single-item-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.add-item-card {
  border: 2px dashed #ccc;
  cursor: pointer;
}

.add-item-card:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.single-item-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.item-icon {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #409eff;
}

.file-icon,
.folder-icon,
.plus-icon {
  width: 1em;
  height: 1em;
}

.file-icon-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border-radius: 4px;
  transition: transform 0.2s;
}

.file-icon-img:hover {
  transform: scale(1.05);
}

.item-info {
  flex: 1;
  overflow: hidden;
}

.item-name {
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  transition: color 0.2s;
}

.item-name:hover {
  color: #409eff;
}

.item-name.no-permission {
  color: #909399;
  cursor: not-allowed;
}

.permission-tag {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 8px;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 4px;
}

.permission-label {
  color: #67c23a;
  font-size: 12px;
  background-color: #f0f9eb;
  padding: 1px 5px;
  border-radius: 3px;
}

.owner-info {
  color: #909399;
  font-size: 12px;
}

.item-meta {
  font-size: 12px;
  color: #606266;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.item-actions {
  display: flex;
  gap: 5px;
  margin-left: 15px;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}

.loading-state {
  margin: 40px 0;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-content p {
  margin-top: 15px;
  color: #606266;
}

.preview-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.preview-loading p {
  margin-top: 15px;
  color: #606266;
}

.preview-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #f56c6c;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.preview-content {
  max-height: 70vh;
  overflow: auto;
  padding: 10px;
}

.image-preview {
  text-align: center;
}

.image-controls {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

.image-container {
  transition: transform 0.3s ease;
  display: inline-block;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.image-info {
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
  text-align: left;
  padding: 0 10px;
}

.text-preview {
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
}

.other-file-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.large-icon {
  font-size: 60px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.text-bold {
  font-weight: bold;
}

.text-danger {
  color: #f56c6c;
}

.hidden {
  display: none;
}

/* 按钮样式优化 - 确保文字居中，图标正确显示 */
.action-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  min-width: 80px;
}

/* 按钮图标样式 */
.button-icon {
  margin-right: 6px;
  width: 1em;
  height: 1em;
}

/* 仅图标按钮样式 */
.icon-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  padding: 0;
}

/* 小尺寸按钮的特殊处理 */
.action-button.el-button--small {
  padding: 0 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
  }

  .header-actions {
    width: 100%;
    justify-content: space-between;
    margin-top: 15px;
  }

  .search-input {
    width: 100%;
  }

  .toolbar-buttons {
    flex-wrap: wrap;
  }

  .item-meta {
    flex-direction: column;
    gap: 5px;
  }

  .item-actions {
    flex-wrap: wrap;
    margin-left: 5px;
  }

  .breadcrumb {
    font-size: 12px;
  }
}
</style> -->